<template>
  <el-dialog :title="textMap[dialogStatus]" width="920px" :visible.sync="dialogFormVisible"
    :close-on-click-modal="false" top="8vh">
    <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="100px"
      v-loading="confirmLoading">
      <el-form-item label="考试类型" prop="type">
        <el-select v-model="form.type" style="width: 100%" placeholder="请选择考试类型" @change="changeType">
          <el-option v-for="item in examTypes" :key="item.key" :label="item.value" :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考试期数" prop="period">
        <el-input placeholder="请输入考试期数" v-model="form.period"></el-input>
      </el-form-item>
      <el-form-item label="考试日期" required style="margin-bottom: 0" v-if="form.examType=='SAFETY_DELAY'">
        <el-col :span="11">
          <el-form-item prop="startTime">
            <el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="开始日期"
              v-model="form.startTime" style="width: 100%;" :picker-options="pickerOptionsStart"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="endTime">
            <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="结束日期" v-model="form.endTime"
              style="width: 100%;" :picker-options="pickerOptionsEnd"></el-date-picker>
            <!-- @change="endTimeChange" -->
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="考试日期" required style="margin-bottom: 0" v-else>
        <el-col :span="11">
          <el-form-item prop="startTime">
            <el-date-picker type="datetime" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="开始日期" v-model="form.startTime" style="width: 100%;" :picker-options="pickerOptionsStart">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="endTime">
            <el-date-picker type="datetime" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期" v-model="form.endTime" style="width: 100%;" :picker-options="pickerOptionsEnd">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="考试时长" prop="singleTime">
        <el-input type="number" placeholder="考试时长" v-model.number="form.singleTime" :disabled="isDisabled">
          <span slot="append">分钟</span>
        </el-input>
      </el-form-item>
      <el-divider>规则设置</el-divider>
      <el-form-item v-for="(item, index) in form.examQusList" :key="item.qusType" :label="item.qusTypeDesc" required
        style="margin-bottom:0">
        <el-col :span="11">
          <el-form-item :prop="'examQusList.' + index + '.qusNum'" :rules="{
            required: true,
            message: '单选题目数量不能为空',
            trigger: 'blur'
          }">
            <el-input placeholder="数量" type="number" v-model="item.qusNum">
              <span slot="prepend">数量</span>
              <span slot="append">个</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item :prop="'examQusList.' + index + '.qusScore'" :rules="{
            required: true,
            message: '单选单个题目分值不能为空',
            trigger: 'blur'
          }">
            <el-input placeholder="单个分值" type="number" v-model="item.qusScore">
              <span slot="prepend">单个分值</span>
              <span slot="append">分</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="满分" prop="totalScore">
            <el-input readonly placeholder="满分" type="number" v-model="form.totalScore">
              <span slot="append">分</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="及格分" prop="passScore">
            <el-input placeholder="及格分" type="number" v-model="form.passScore">
              <span slot="append">分</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-card v-for="(item, index) in form.examCfgList" :key="index" shadow="never" class="custom-exam-card">
        <div slot="header" class="clearfix">
          <el-row type="flex" justify="end">
            <el-button @click.prevent="handleRemove(item)" type="danger" icon="el-icon-delete" circle title="删除" plain
              v-if="form.examCfgList.length > 1"></el-button>
            <el-button type="primary" icon="el-icon-plus" circle title="添加" plain @click="handleAdd"
              v-if="index === form.examCfgList.length-1"></el-button>
          </el-row>
        </div>
        <el-form-item :key="index" label="工种" style="margin-bottom:0" required>
          <el-col :span="11">
            <el-form-item :prop="'examCfgList.' + index + '.targetRole'" :rules="{
              required: true,
              message: '请选择',
              trigger: 'change'
            }">
              <el-select v-model="item.targetRole" style="width: 100%" placeholder="请选择工种">
                <el-option v-for="item in workTypeList" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item :prop="'examCfgList.' + index + '.qusLibId'" :rules="{
              required: true,
              message: '请选择',
              trigger: 'change'
            }">
              <el-select multiple v-model="item.qusLibId" style="width: 100%" placeholder="请选择题库">
                <el-option v-for="item in qusLibList" :key="item.id" :label="item.libName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-row :gutter="24">
          <el-col :span="8" v-for="(ratio, order) in item.examRatioList" :key="order">
            <el-form-item :key="order" :label="ratio.qusPropTypeDesc"
              :prop="'examCfgList.' + index + '.examRatioList.' + order + '.qusRadio'" label-width="135px" :rules="{
                required: true,
                message: '请选择',
                trigger: 'change'
              }">
              <el-input placeholder="占比" type="number" v-model="ratio.qusRadio">
                <span slot="append">%</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        取消
      </el-button>
      <el-button :loading="confirmLoading" type="primary" @click="submitForm">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import formMixin from "@/mixins/form";
import request from "@/utils/request";
export default {
  name: "Dialog",
  mixins: [formMixin],
  components: {},
  data() {
    return {
      textMap: {
        update: "考试设置",
        create: "考试设置"
      },
      rules: {
        type: [
          {
            required: true,
            message: "请选择",
            trigger: "blur"
          }
        ],
        period: [
          {
            required: true,
            message: "请设置考试期数名称",
            trigger: "blur"
          }
        ],
        startTime: [
          {
            required: true,
            message: "请选择考试开始日期",
            trigger: "change"
          }
        ],
        endTime: [
          {
            required: true,
            message: "请选择考试结束日期",
            trigger: "change"
          }
        ],
        singleTime: [
          {
            required: false,
            message: "请选择",
            trigger: "blur"
          }
        ],
        totalScore: [
          {
            required: true,
            message: "请输入满分分值",
            trigger: "blur"
          }
        ],
        passScore: [
          {
            required: true,
            message: "请输入及格分值",
            trigger: "blur"
          }
        ]
      },
      qusLibList: [],
      Urls: {
        qusLibListUrl: "/api/question/lib/list",
        addUrl: "/api/exam/insert",
        editUrl: "/api/exam/update/",
        getByIdUrl: "/api/exam/detail/get/",
        dictTypeUrl: '/api/dict/typeList',
      },
      examTypes: [
        {
          key: 'SAFETY_NEW',
          value: '安管人员新办'
        },
        {
          key: 'SAFETY_DELAY',
          value: '安管人员延期'
        },
        {
          key: 'SPECIAL_EQP',
          value: '特种设备'
        },
      ],
      examToWorkType: {
        SAFETY_NEW: 'safty_type',
        SAFETY_DELAY: 'safty_type',
        SPECIAL_EQP: 'special_type',
      },
      examToQusType: {
        SAFETY_NEW: 'safty_qus_type',
        SAFETY_DELAY: 'safty_qus_type',
        SPECIAL_EQP: 'special_qus_type',
      },
      qus_type: [],
      workTypeList: []
    };
  },
  computed: {
    isDisabled() {
      console.log(111, this.form.type)
      if (this.form.type == 'SAFETY_DELAY') {
        this.form.singleTime = 120
        return false
      }
      this.form.singleTime = ""
      return true
    }
  },
  watch: {
    "form.examQusList": {
      handler(newVal, oldVal) {
        if (newVal.length > 0) {
          let total = 0;
          this.form.examQusList.map(item => {
            total = total + (item.qusNum || 0) * (item.qusScore || 0);
          });
          this.form.totalScore = total;
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * 切换考试类型
     * @param {Object} val
     */
    changeType(val) {
      // 切换工种
      this.getDictData(this.examToWorkType[val], 'workTypeList')
      // 切换考试内容
      this.getDictData(this.examToQusType[val], 'qus_type')
    },
    handleRemove(record) {
      const index = this.form.examCfgList.indexOf(record)
      if (index !== -1) {
        this.form.examCfgList.splice(index, 1)
      }
    },
    handleAdd() {
      let examCfgList = this.form.examCfgList
      let examRatioList = []
      for (var i = 0; i < this.qus_type.length; i++) {
        examRatioList.push({
          qusPropType: this.qus_type[i].key,
          qusPropTypeDesc: this.qus_type[i].value,
          qusRadio: 10,
        })
      }
      examCfgList.push({
        targetRole: '',
        qusLibId: [],
        examRatioList: examRatioList
      })
      this.$set(this.form, 'examCfgList', examCfgList)
    },
    beforeOpen(row) {
      if (row && row.type) {
        this.changeType(row.type)
      } else {
        // 工种
        this.getDictData('safty_type', 'workTypeList')
        // 考试内容
        this.getDictData('safty_qus_type', 'qus_type')
      }
      this.getQusLibList();
    },
    resetForm() {

      this.form = {
        examQusList: [
          { qusType: "choice", qusTypeDesc: "单选", qusNum: 50, qusScore: 1 },
          { qusType: "judge", qusTypeDesc: "判断", qusNum: 50, qusScore: 1 }
        ],
        examCfgList: [
          /* { targetRole: '', qusLibId: [], examRatioList: [
             {
               qusPropType: '01',
               qusPropTypeDesc: '安全生产基本知识',
               qusRadio: 10,
             },
             {
               qusPropType: '02',
               qusPropTypeDesc: '专业基础知识',
               qusRadio: 10,
             },
             {
               qusPropType: '03',
               qusPropTypeDesc: '专业技术理论',
               qusRadio: 10,
             },
           ]}, */
        ]
      };
      console.log(this.form)
    },
    fillForm(data) {
      this.$nextTick(() => {
        let examCfgList = []
        for (var i = 0; i < data.examCfgList.length; i++) {
          data.examCfgList[i].qusLibId = data.examCfgList[i].qusLibIds.split(",");
          examCfgList.push(data.examCfgList[i])
        }
        this.$set(this.form, 'examCfgList', examCfgList)
      })
    },
    formatData(data) {
      let form = Object.assign({}, data);
      let examCfgList = []
      for (var i = 0; i < form.examCfgList.length; i++) {
        form.examCfgList[i]['targetRoleName'] = this.getTypeDesc('key', form.examCfgList[i].targetRole, 'value', this.workTypeList)
        form.examCfgList[i]['qusLibIds'] = form.examCfgList[i].qusLibId.join()
        form.examCfgList[i]['qusLibNames'] = this.getqusLibName(form.examCfgList[i].qusLibId)
        form.examCfgList[i]['period'] = form.period
        form.examCfgList[i]['type'] = form.type
        examCfgList.push(form.examCfgList[i])
      }
      form.examCfgList = [...examCfgList]
      console.log(form)
      return form;
    },
    /**
     * 获取desc
     * @param {String} key
     * @param {String} value
     * @param {String} descKey
     * @param {Array} arr
     */
    getTypeDesc(key, value, descKey, arr) {
      let typeDesc = ''
      for (var i = 0; i < arr.length; i++) {
        if (arr[i][key] === value) {
          typeDesc = arr[i][descKey]
          break
        }
      }
      return typeDesc
    },
    // 时间格式
    endTimeChange(date) {
      this.form.endTime = `${date} 23:59:59`;
      console.log(this.form.endTime)
    },
    // 获取一级字典数据
    getDictData(type, data) {
      request({
        url: this.Urls.dictTypeUrl,
        method: 'get',
        params: {
          type: type
        }
      }).then(res => {
        if (res.code == 0) {
          this[data] = res.data.records
          this.afterGetDict(data)
        } else {
          that.$notify({
            title: "提示",
            message: res.msg,
            type: "error",
            duration: 2000
          });
        }
      })
    },
    afterGetDict(data) {
      if (data === 'qus_type') {
        let examRatioList = []
        for (var i = 0; i < this[data].length; i++) {
          examRatioList.push({
            qusPropType: this[data][i].key,
            qusPropTypeDesc: this[data][i].value,
            qusRadio: 10,
          })
        }
        this.form.examCfgList = [{
          targetRole: '',
          qusLibId: [],
          examRatioList: examRatioList
        }]
      }
    },
    // 获取题库
    getQusLibList() {
      request({
        url: this.Urls.qusLibListUrl,
        method: "get"
      })
        .then(res => {
          console.log("form list", res);
          if (res.code == 0) {
            this.qusLibList = res.data.records || [];
          } else {
            that.$notify({
              title: "提示",
              message: res.msg,
              type: "error",
              duration: 2000
            });
          }
        })
        .catch(err => {
          that.dialogFormVisible = false;
        });
    },
    getqusLibName(val) {
      console.log(val);
      let ids = val,
        arr = this.qusLibList,
        names = [];
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < ids.length; j++) {
          if (ids[j] == arr[i].id) {
            names.push(arr[i].libName);
          }
        }
      }

      /* let obj = this.qusLibList.find(item => {
        return item.id === val;
      }); */
      console.log("题库", names);
      this.form.qusLibNames = names.join(",");
      return names.join(",")
    }
  },
  created() { },
  mounted() { },
  beforeCreate() { },
  beforeMount() { },
  beforeUpdate() { },
  updated() { },
  beforeDestroy() { },
  destroyed() { },
  activated() { }
};
</script>
<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>
